<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <div>
        <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
      </div>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bd',ind===0?'td':'']"
              v-for="(item1,ind) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级数据渲染区域 -->
              <el-col :span="5">
                <el-tag type="success">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级数据区域 -->
              <el-col :span="19">
                <el-row
                  :class="index === 0?'':'td'"
                  v-for="(item2,index) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <!-- 二级数据渲染区域 -->
                    <el-tag type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级数据渲染区域 -->
                    <el-tag
                      closable
                      @close="removeTag(scope.row,item3.id)"
                      v-for="item3 in item2.children"
                      type="warning"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              type="primary"
              @click="changeEditStatus(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              icon="el-icon-delete"
              type="danger"
              @click="removeRole(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              icon="el-icon-setting"
              type="warning"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="50%" @close="clearDialog">
      <!-- 主题内容 -->
      <el-form
        :model="addRoleForm"
        :rules="addRoles"
        ref="addRoleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="提示" :visible.sync="editDialogVisible" width="50%" @close="clearEditDialog">
      <!-- 主题内容 -->
      <el-form
        :model="editRoleForm"
        :rules="editRoles"
        ref="editRoleFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" width="50%"
    @close="setRightsDialogClosed">
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKey"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      //添加角色对话框
      addRoleForm: {
        roleName: "",
        roleDesc: ""
      },
      //编辑角色对话框存储对象
      editRoleForm: {
        roleName: "",
        roleDesc: ""
      },
      //存储所有权限列表的对象
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        children: "children",
        label: "authName"
      },
      //   默认选中的节点id值数组
      defKey:[],
      //   存储当前分配角色的id值
      roleId:'',
      //添加角色对话框的隐藏和显示
      dialogVisible: false,
      //   编辑角色对话框的隐藏和显示
      editDialogVisible: false,
      //   分配权限对话框的显示与隐藏
      setRightsDialogVisible: false,
      // 添加角色表单的校验规则
      addRoles: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ]
      },
      // 修改角色表单的校验规则
      editRoles: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表信息失败");
      this.rolesList = res.data;
    },
    // 添加角色事件
    addRole() {
      // 判断表单是否填写完整
      this.$refs.addRoleFormRef.validate(async flag => {
        if (!flag) return this.$message.error("请完善表单");
        // 发送添加角色请求
        const { data: res } = await this.$http.post("roles", this.addRoleForm);
        // 如果创建失败
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        // 创建成功 提示用户创建成功
        this.$message.success("创建角色成功");
        // 重渲染
        this.getRolesList();
        // 关闭对话框
        this.dialogVisible = false;
      });
    },
    //  清空对话框数据
    clearDialog() {
      this.$refs.addRoleFormRef.resetFields();
      this.addRoleForm = {
        roleName: "",
        roleDesc: ""
      };
    },
    //  清空编辑角色对话框数据
    clearEditDialog() {
      this.$refs.editRoleFormRef.resetFields();
    },
    // 删除角色
    removeRole(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          // 发起删除请求
          const { data: res } = await this.$http.delete("roles/" + id);
          // 如果删除失败
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          //删除成功
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          //   重渲染角色列表
          this.getRolesList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 显示修改角色对话框
    async changeEditStatus(id) {
      // 根据id查询角色
      const { data: res } = await this.$http.get("roles/" + id);
      this.editRoleForm = res.data;
      this.editDialogVisible = true;
    },
    // 修改用户
    editRole() {
      this.$refs.editRoleFormRef.validate(async flag => {
        if (!flag) return this.$message.error("请完善表单");
        // 发送修改角色请求
        const { data: res } = await this.$http.put(
          "roles/" + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc
          }
        );
        // 修改失败
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        // 修改成功 提示修改成功 关闭修改对话框 重渲染角色列表数据
        this.$message.success("修改角色成功");
        this.editDialogVisible = false;
        this.getRolesList();
      });
    },
    // 删除权限
    removeTag(role, right) {
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "再想想",
        type: "warning"
      })
        .then(async () => {
          // 发起删除请求
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${right}`
          );
          //   取消失败 提示用户
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          role.children = res.data;
        })
        .catch(() => {
          this.$message("已取消删除");
        });
    },
    // 显示分配权限对话框
    async showSetRightDialog(role) {
    //   将当前分配权限的角色id存储到data属性中
      this.roleId = role.id;     
      const { data: res } = await this.$http.get("rights/tree");
      // 如果获取失败
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      // 如果获取成功
      // 将获取到的数据保存到data中
      this.rightsList = res.data;
      
      this.getLeafKeys(role,this.defKey);

      this.setRightsDialogVisible = true;
    },
    // 根据递归函数获取当前角色的已有权限id值 并将获取的id存储到this.defKey中
    getLeafKeys(node,arr){
        if(!node.children){
            return arr.push(node.id)
        }

        node.children.forEach(item =>{
            this.getLeafKeys(item,arr)
        })
    },
    // 监听权限分配管理对话框的关闭事件
    setRightsDialogClosed(){
        this.defKey = [];
    },
    // 点击为角色分配权限
    async allotRights(){
        console.log(this.$refs.treeRef.getCheckedKeys());
        
        const keys = [
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        // 将修改过后的权限id数据转化为以逗号分隔的字符串
        const idStr = keys.join(',')
        // 调用API
        const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{
            rids:idStr
        })
        // 分配失败
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg);
        // 分配成功 关闭分配权限对话框 重绘数据
        this.$message.success('分配权限成功')
        this.setRightsDialogVisible = false
        this.getRolesList();
        
        
        
    }
  }
};
</script>
<style scoped lang="less">
.el-tag {
  margin: 7px;
}
.el-row {
  display: flex;
  align-items: center;
}
.bd {
  border-bottom: 1px solid #eee;
}
.td {
  border-top: 1px solid #eee;
}
</style>